<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    @close="closeDialog"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model.trim="form.roleCode" />
      </el-form-item>
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model.trim="form.roleName" />
      </el-form-item>
      <el-form-item label="角色备注" prop="roleMemo">
        <el-input v-model.trim="form.roleMemo" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
  import { ref, reactive } from 'vue'
  import { addRoleApi, updateRoleApi } from '@/api/comdesk/role'
  const $baseLoading = inject('$baseLoading')
  const $baseMessage = inject('$baseMessage')
  // ---- import

  const _emit = defineEmits(['success-callback'])
  // ---- init
  const dialogTitle = ref('新增')
  const dialogVisible = ref(false)
  import { localStorageConfig } from '@/config/localstorage.config'
  const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)

  const formRef = ref(null)
  const form = reactive({ roleCode: '', roleName: '', roleMemo: '' })
  const rules = reactive({
    roleCode: [{ required: true, trigger: 'blur', message: '请输入角色编码' }],
    roleName: [{ required: true, trigger: 'blur', message: '请输入角色名称' }],
  })
  let baseRecord = null

  const toOpenDialog = (record) => {
    dialogVisible.value = true
    if (record) {
      dialogTitle.value = '修改'
      baseRecord = record
      form['pkRole'] = record.pkRole ? record.pkRole : ''
      form['roleCode'] = record.roleCode ? record.roleCode : ''
      form['roleName'] = record.roleName ? record.roleName : ''
      form['roleMemo'] = record.roleMemo ? record.roleMemo : ''
      form['pkCorp'] = pkCorp
    } else {
      dialogTitle.value = '新增'
      form['roleCode'] = ''
      form['roleName'] = ''
      form['roleMemo'] = ''
      form['pkCorp'] = pkCorp
    }
  }

  const save = () => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        const load = $baseLoading()
        try {
          let res = null
          if (baseRecord) {
            res = await updateRoleApi(form)
          } else {
            res = await addRoleApi(form)
          }
          load.close()
          if (res && res.code === 2000) {
            $baseMessage(res && res.msg ? res.msg : '操作成功', 'success')
            closeDialog()
            _emit('success-callback')
          } else {
            $baseMessage(res && res.msg ? res.msg : '操作失败', 'error')
          }
        } catch (e) {
          load.close()
        }
      }
    })
  }

  const closeDialog = () => {
    baseRecord = null
    dialogVisible.value = false
  }

  defineExpose({ toOpenDialog })
</script>
